package framework

import (
	"../global"
	"github.com/dxvgef/token"
	"github.com/labstack/echo"
)

//token中间件
func CheckToken(key string, method string, paramName string) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(ctx echo.Context) error {
			//声明响应给客户端的map用于转化成json
			response := make(map[string]interface{})
			//初始化error字段为空
			response["error"] = ""

			//defer func() {
			//	if recover() != nil {
			//		response["error"] = "发生恐慌"
			//		ctx.JSON(500, response)
			//	}
			//}()

			var tokenStr string

			switch method {
			case "header":
				tokenStr = ctx.Request().Header.Get(paramName)
			case "get":
				tokenStr = ctx.QueryParam(paramName)
			case "post":
				tokenStr = ctx.FormValue(paramName)
			case "path":
				tokenStr = ctx.Param(paramName)
			case "cookie":
				tok, err := ctx.Cookie(paramName)
				if err != nil {
					response["error"] = "无法从cookie中获取token"
				}
				tokenStr = tok.String()
			}

			var t *token.Token
			var err error
			t, err = token.Parse(tokenStr, &global.TokenClaims{}, key)
			if err != nil {
				global.Logger.Error("token解析失败：" + err.Error())
				response["error"] = err.Error()
				return ctx.JSON(403, response)
			}

			if t.Claims.Activated() == false {
				response["error"] = "token未激活"
				return ctx.JSON(403, response)
			}

			if t.Claims.Expired() == true {
				response["error"] = "token已失效"
				return ctx.JSON(403, response)
			}
			ctx.Set("adminTokenClaims", t.Claims)

			return next(ctx)
		}

	}
}
